﻿using System;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Configuration;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Runtime.InteropServices;
using Openfree.Framework.DataAccess;
using ConvertEx = Openfree.Framework.Common.Convert;
using LogTypeEx = Openfree.Framework.DataAccess.LogType;

public class GroupAccess
{
    public SqlConnection Connection;

    public GroupAccess(SqlConnection conn)
    {
        Connection = conn;
    }

    public long GroupSignFileSize()
    {
        CodeConfigAccess codeConfig = new CodeConfigAccess(Connection);
        string result = codeConfig.GetCodeValue("System", "GroupSignFileSize");
        return long.Parse(result);
    }

    /// <summary>
    /// 从系统配置表中取用户资源存储ID
    /// </summary>
    /// <returns></returns>
    public string GetGroupStoreLocationID()
    {
        CodeConfigAccess codeConfig = new CodeConfigAccess(Connection);
        return codeConfig.GetCodeValue("SYSTEM", "GroupStoreLocation");
    }

    public DataSet GetGroup(string groupID)
    {
        string cmdText = @"select * from T_Group where GroupID='{0}' order by CreateDate desc";
        cmdText = string.Format(cmdText, groupID.Replace("'",""));
        return BaseAccess.GetDataSet(Connection, cmdText, "T_Group");
    }

    public DataSet GetGroupAllInfo(string groupID)
    {
        string cmdText = @"select a.*, b.CodeName, b.Description as CCDescription 
            from T_Group a left join T_CodeConfig b on a.Category=b.CodeValue and 
            a.GroupID='{0}; andb.Category='GroupCategory' order by CreateDate desc";
        cmdText = string.Format(cmdText, groupID.Replace("'", ""));
        return BaseAccess.GetDataSet(Connection, cmdText, "T_Group");
    }

    public int GetGroupCategory(string groupID)
    {
        string cmdText = "select Category from T_Group where GroupID='{0}'";
        cmdText = string.Format(cmdText, groupID);
        return Convert.ToInt32(BaseAccess.ExecuteScalar(Connection, cmdText));
    }

    public string GetUserCount(string groupID)
    {
        string cmdText = @"select UserCount from T_Group where GroupID='{0}'";
        cmdText = string.Format(cmdText, groupID.Replace("'", "''"));
        return BaseAccess.ExecuteScalar(Connection, cmdText);
    }

    public void RemoveGroup(string groupID)
    {
        
            //删除小组文件夹
            string storeLocationID = BaseAccess.ExecuteScalar(Connection,
                "select StoreLocationID from T_Group where GroupID='" + groupID + "'");
            string folderName = StoreLocationAccess.GetLocalDirectory(storeLocationID);
            folderName = folderName + groupID;
            Openfree.Framework.Common.ShareCommon.DeleteFolder(folderName);

            //删除小组话题Tag


            //删除小组Tag


            //删除小组产生的数据
            BaseAccess.ExecuteNonQuery(Connection,
                "delete from T_GroupTopic where GroupID='" + groupID + "'");

            //删除小组人员
            BaseAccess.ExecuteNonQuery(Connection,
               "delete from T_GroupUser where GroupID='" + groupID + "'");

            //删除小组
            BaseAccess.ExecuteNonQuery(Connection,
                "delete from T_Group where GroupID='" + groupID + "'");
        
    }

    public DataSet LoadGroupCategory()
    {
        CodeConfigAccess codeConfig = new CodeConfigAccess(Connection);
        return codeConfig.LoadDataByCategory("GroupCategory");
    }

    public static string GetGroupSignURL(string storeLocationID, DateTime createDate, string groupID, string fileName)
    {
        string URL = StoreLocationAccess.GetLocalResourceDirectory(storeLocationID, createDate, groupID);        
        if (!System.IO.File.Exists(URL + "\\" + fileName))
        {
            URL = "App_Themes/DefaultSkin/Image/groupSign.jpg";
        }
        else
        {
            URL = StoreLocationAccess.GetVirtualDirectory(storeLocationID);
            URL = URL + "/" + createDate.ToString("yyyy") + "/" + createDate.ToString("MM") + "/" +
                createDate.ToString("dd") + "/" + groupID + "/" + fileName;
        }
        return URL;
    }

    public int AddGroupUser(string groupID, string userID)
    {
        if (string.IsNullOrEmpty(groupID) ||
            string.IsNullOrEmpty(userID))
        {
            return 0;
        }
        string cmdText = "insert into T_GroupUser(GroupID, UserID, IsAdmin, IsKill) values('{0}','{1}', 0, 0)";
        cmdText = string.Format(cmdText, groupID, userID);
        return BaseAccess.TryExecuteNonQuery(Connection, cmdText);
    }

    public int RemoveGroupUser(string groupID, string userID)
    {
        string cmdText = "delete T_GroupUser where GroupID='{0}' and UserID='{1}'";
        cmdText = string.Format(cmdText, groupID, userID);        
        int result = BaseAccess.TryExecuteNonQuery(Connection, cmdText);
        UpdateUserCount(groupID);
        return result;
    }

    public int UpdateGroupUser(string groupID, string userID, int isAdmin)
    {
        string cmdText = "update T_GroupUser set IsAdmin='{2}' where GroupID='{0}' and UserID='{1}'";
        cmdText = string.Format(cmdText, groupID, userID, isAdmin);
        return BaseAccess.TryExecuteNonQuery(Connection, cmdText);
    }

    public int KillGroupUser(string groupID, string userID)
    {
        string cmdText = "update T_GroupUser set IsKill=1 where GroupID='{0}' and UserID='{1}'";
        cmdText = string.Format(cmdText, groupID, userID);
        int result = BaseAccess.TryExecuteNonQuery(Connection, cmdText);
        UpdateUserCount(groupID);
        return result;
    }

    public void UpdateUserCount(string groupID)
    {
        string cmdText = "update T_Group set UserCount=(select count(*) from T_GroupUser where GroupID='{0}' and IsKill=0) where GroupID='{0}'";
        cmdText = string.Format(cmdText, groupID);
        BaseAccess.TryExecuteNonQuery(Connection, cmdText);
    }

    /// <summary>
    /// 判断用户是否存在，返回-2永久踢出小组，-1没登录，返回0非小组成员，
    /// 返回1小组成员，返回2管理员，返回3创建人，返回4是admin
    /// </summary>
    /// <param name="groupID"></param>
    /// <param name="loginName"></param>
    /// <returns></returns>
    public int GroupExistsUser(string groupID, string userID)
    {
        if (string.IsNullOrEmpty(userID))
        {
            return -1;
        }
        string cmdText = "select IsKill from T_GroupUser where GroupID='{0}' and UserID='{1}'";
        cmdText = string.Format(cmdText, groupID, userID);
        cmdText = BaseAccess.ExecuteScalar(Connection, cmdText);
        if (cmdText.ToLower() == "1" ||
            cmdText.ToLower() == "true")
        {
            return -2;
        }
        cmdText = "select UserID from T_User where UserID='{0}'";
        cmdText = string.Format(cmdText, userID);
        cmdText = BaseAccess.ExecuteScalar(Connection, cmdText);
        if (cmdText.ToLower() == "admin" ||
            cmdText.ToLower() == "administrator")
        {
            return 4;
        }
        cmdText = "select UserID from T_Group where GroupID='{0}' and UserID='{1}'";
        cmdText = string.Format(cmdText, groupID, userID);
        cmdText = BaseAccess.ExecuteScalar(Connection, cmdText);
        if (!string.IsNullOrEmpty(cmdText))
        {
            return 3;
        }
        cmdText = "select UserID from T_GroupUser where GroupID='{0}' and UserID='{1}' and IsAdmin=1";
        cmdText = string.Format(cmdText, groupID, userID);
        cmdText = BaseAccess.ExecuteScalar(Connection, cmdText);
        if (!string.IsNullOrEmpty(cmdText))
        {
            return 2;
        }
        cmdText = "select UserID from T_GroupUser where GroupID='{0}' and UserID='{1}'";
        cmdText = string.Format(cmdText, groupID, userID);
        cmdText = BaseAccess.ExecuteScalar(Connection, cmdText);   
        if (!string.IsNullOrEmpty(cmdText))
        {
            return 1;
        }
        return 0;
    }

    public int GroupInviteUser(string groupID, string userID)
    {
        string cmdText = "update T_GroupUser set Invited='0' where GroupID='{0}' and UserID in ({1})";
        cmdText = string.Format(cmdText, groupID, userID);
        return BaseAccess.TryExecuteNonQuery(Connection, cmdText);
    }
}


public class GroupTopicAccess
{
    public SqlConnection Connection;

    public GroupTopicAccess(SqlConnection conn)
    {
        Connection = conn;
    }

    public DataSet GetTopic(string topicID)
    {
        string cmdText = "select * from T_GroupTopic where TopicID='{0}'";
        cmdText = string.Format(cmdText, topicID.Replace(",", ""));
        return BaseAccess.GetDataSet(Connection, cmdText, "T_GroupTopic");
    }

    public DataSet GetTopicFeedback(string topicID)
    {
        string cmdText = "select * from T_GroupTopicFeedback where TopicID='{0}'";
        cmdText = string.Format(cmdText, topicID.Replace(",", ""));
        return BaseAccess.GetDataSet(Connection, cmdText, "T_GroupTopicFeedback");
    }

    public void UpdateTopic(DataSet dsTopic)
    {
        BaseAccess.UpdateDataSet(Connection, "T_GroupTopic", dsTopic);
    }

    public void UpdateTopicFeedback(DataSet dsTopicFeedback)
    {
        BaseAccess.UpdateDataSet(Connection, "T_GroupTopicFeedback", dsTopicFeedback);
    }

    public void UpdateLastFeedbackState(string topicID)
    {
        string cmdText = "update T_GroupTopic set LastFeedbackDate=GetDate() where TopicID='{0}'";
        cmdText = string.Format(cmdText, topicID);
        BaseAccess.TryExecuteNonQuery(Connection, cmdText);
        cmdText = "update T_GroupTopic set FeedbackCount=(select count(*) from T_GroupTopicFeedback  where TopicID='{0}') where TopicID='{0}'";
        cmdText = string.Format(cmdText, topicID);
        BaseAccess.TryExecuteNonQuery(Connection, cmdText);
    }
}


public class UserAccess : SqlUserAccess
{
    public const string TABLE_USER = "T_User";
    
    public UserAccess(SqlConnection conn)
        : base(conn)
    {        
    }

    protected override void InitTableName()
    {
        this.TableName = TABLE_USER;
    }

    protected override void InitCommandParameters(ref SqlParameterCollection pc)
    {
        pc.Add(new SqlParameter("@StoreLocationID", SqlDbType.VarChar, 36));
        pc["@StoreLocationID"].SourceColumn = "StoreLocationID";
        pc.Add(new SqlParameter("@Country", SqlDbType.VarChar, 50));
        pc["@Country"].SourceColumn = "Country";
        pc.Add(new SqlParameter("@City", SqlDbType.VarChar, 50));
        pc["@City"].SourceColumn = "City";
        pc.Add(new SqlParameter("@Province", SqlDbType.VarChar, 64));
        pc["@Province"].SourceColumn = "Province";
        pc.Add(new SqlParameter("@Area", SqlDbType.VarChar, 64));
        pc["@Area"].SourceColumn = "Area";
    }

    public override bool UpdateUser(DataSet dataSet)
    {
        foreach (DataRow row in dataSet.Tables[0].Rows)
        {
            if (row.RowState == DataRowState.Added)
            {
                StoreLocationAccess.CreateLocalResourceDirectory(row["StoreLocationID"].ToString(),
                    Convert.ToDateTime(row["CreateDate"].ToString()), row["UserID"].ToString());
            }
        }
        return base.UpdateUser(dataSet);
    }

    public override bool DeleteUserByUserID(string userID)
    {
        string path = GetLocalResourceDirectory(userID);
        if (System.IO.Directory.Exists(path))
        {
            Openfree.Framework.Common.ShareCommon.DeleteFolder(path);
        }
        return base.DeleteUserByUserID(userID);
    }

    public string GetNavigation(int currentPageIndex)
    {
        return base.GetNavigation(currentPageIndex, string.Empty, "userManager.aspx");
    }

    public bool ExistUser(string loginName)
    {
        DataSet dsUser = base.GetUserByLoginName(loginName, true);
        if (dsUser != null && dsUser.Tables.Count > 0 && dsUser.Tables[0].Rows.Count > 0)
        {
            dsUser.Dispose();
            return true;
        }
        else
        {
            dsUser.Dispose();
            return false;
        }
    }

    public bool ExistUserFriend(string userID, string friendUserID)
    {
        string cmdText = "select friendUserID from T_UserFriend where UserID='{0}' and friendUserID='{1}'";
        cmdText = string.Format(cmdText, userID, friendUserID);
        cmdText = BaseAccess.ExecuteScalar(base.Connection, cmdText);
        if (string.IsNullOrEmpty(cmdText))
        {
            return false;
        }
        return true;
    }

    public bool ValidateUsername(string username)
    {
        CodeConfigAccess codeConfig = new CodeConfigAccess(base.Connection);
        DataSet ds = codeConfig.LoadDataByCategory("UsernameKeyword");
        if (ds.Tables[0].Select("CodeValue='" + username.Trim().ToLower().Replace("'", "''") + "'").Length > 0)
        {
            return true;
        }
        return false;
    }

    /// <summary>
    /// 从系统配置表中取用户资源存储ID
    /// </summary>
    /// <returns></returns>
    public string GetUserStoreLocationID()
    {
        CodeConfigAccess codeConfig = new CodeConfigAccess(base.Connection);
        return codeConfig.GetCodeValue("System", "UserStoreLocation");
    }

    public long UserSignFileSize()
    {
        CodeConfigAccess codeConfig = new CodeConfigAccess(base.Connection);
        string result = codeConfig.GetCodeValue("System", "UserSignFileSize");
        return long.Parse(result);
    }

    public string GetUserSignURL(string userID)
    {
        DataSet ds = GetUserByUserID(userID, true);
        DataRow row = ds.Tables[0].Rows[0];
        string URL = StoreLocationAccess.GetVirtualDirectory(row["StoreLocationID"].ToString());
        string fileName = userID.Substring(0, userID.IndexOf("-")) + ".jpg";
        DateTime time = Convert.ToDateTime(row["CreateDate"].ToString());
        URL = URL + "/" + time.ToString("yyyy") + "/" + time.ToString("MM") + "/" + time.ToString("dd") + "/" +
            row["UserID"].ToString() + "/" + fileName;
        return URL;
    }

    public static string GetUserSignURL(string storeLocationID, DateTime createDate, string userID)
    {
        string URL = StoreLocationAccess.GetLocalResourceDirectory(storeLocationID, createDate, userID);
        string fileName = userID.Substring(0, userID.IndexOf("-")) + ".jpg";
        if (!System.IO.File.Exists(URL + fileName))
        {
            URL = "App_Themes/DefaultSkin/Image/userSign.jpg";
        }
        else
        {
            URL = StoreLocationAccess.GetVirtualDirectory(storeLocationID);
            URL = URL + "/" + createDate.ToString("yyyy") + "/" + createDate.ToString("MM") + "/" +
                createDate.ToString("dd") + "/" + userID + "/" + fileName;
        }
        return URL;
    }

    /// <summary>
    /// 取得用户资源存储本地路径，结尾含"\"
    /// </summary>
    /// <param name="loginName"></param>
    /// <returns></returns>
    public string GetLocalResourceDirectory(string userID)
    {
        //todo 应该可以合并  StoreLocationAccess的同名方法
        DataSet ds = GetUserByUserID(userID, true);
        DataRow row = ds.Tables[0].Rows[0];
        string path = StoreLocationAccess.GetLocalDirectory(row["StoreLocationID"].ToString());
        path = path.TrimEnd('\\') + "\\";
        DateTime time = Convert.ToDateTime(row["CreateDate"].ToString());
        path += time.ToString("yyyy") + "\\" + time.ToString("MM") + "\\" + time.ToString("dd") + "\\" +
            row["UserID"].ToString() + "\\";
        ds.Dispose();
        return path;
    }

    /// <summary>
    /// 创建用户资源存储本地路径，并且返回创建后的路径，结尾含"\"
    /// </summary>
    /// <param name="loginName"></param>
    /// <returns></returns>
    public string CreateLocalResourceDirectory(string loginName)
    {//todo 应该可以合并  StoreLocationAccess的同名方法
        string path = GetLocalResourceDirectory(loginName);
        if (!System.IO.Directory.Exists(path))
        {
            System.IO.Directory.CreateDirectory(path);
        }
        return path;
    }

    public string GetUserOrgID(string userID)
    {
        string cmdText = @"select OrgID from T_OrgUser where UserID = '{0}'";
        cmdText = string.Format(cmdText, userID);
        return BaseAccess.ExecuteScalar(base.Connection, cmdText);
    }

    public string GetUserGroupCode(string userID)
    {
        string cmdText = @"select GroupCode from PMS_User where UserID = '{0}'";
        cmdText = string.Format(cmdText, userID);
        return BaseAccess.ExecuteScalar(base.Connection, cmdText);
    }
    public string GetUserOrgName(string userID)
    {
        string cmdText = @"select b.Subject from T_OrgUser a left join T_OrgPool b 
            on a.OrgID=b.OrgID where a.UserID = '{0}'";
        cmdText = string.Format(cmdText, userID);
        return BaseAccess.ExecuteScalar(base.Connection, cmdText);
    }

    public static string GetUserOrgName(SqlConnection conn, string userID)
    {
        string cmdText = @"select b.Subject from T_OrgUser a left join T_OrgPool b 
            on a.OrgID=b.OrgID where a.UserID = '{0}'";
        cmdText = string.Format(cmdText, userID);
        return  BaseAccess.ExecuteScalar(conn, cmdText);
    }

//    public static string GetUserOrgNameByLoginName(SqlConnection conn, string loginName)
//    {
//        string result = string.Empty;
//        string cmdText = @"select a.*, b.Subject from T_OrgUser a left join T_OrgTree b 
//            on a.OrgID=b.NodeID where a.UserID = (select top UserID from T_User where LoginName='{0}')";
//        cmdText = string.Format(cmdText, row["UserID"].ToString());
//        DataSet dsOrg = BaseAccess.GetDataSet(base.Connection, cmdText);
//        if (dsOrg.Tables[0].Rows.Count > 0)
//        {
//            result = dsOrg.Tables[0].Rows[0]["Subject"].ToString();
//        }
//        return result;
//    }
}


public class SecurityAccess : SqlSecurity
{
    public SecurityAccess(SqlConnection conn)
        : base(conn)
    {

    }
}


public class DocumentAccess
{
    public static void AddViewCount(string documentID, string tableName)
    {
        documentID = documentID.Replace(",",string.Empty);
        BaseAccess.ExecuteNonQuery(ConfigManager.ConnectionString,
            "update " + tableName + " set ViewCount = ViewCount + 1 where DocumentID='" + documentID + "'");
    }

    public static DataSet GetDataSet(string documentID, string tableName)
    {
        return BaseAccess.GetDataSet(ConfigManager.ConnectionString,
                "select * from " + tableName + " where DocumentID = '" + documentID + "'", "T_Document");
    }        
}


public class DocumentCategoryAccess : SqlTree
{
    public const string TABLE_NAME = "T_DocumentCategory";

    public DocumentCategoryAccess(SqlConnection conn)
        : base(conn)        
    {

    }

    protected override void InitTableName()
    {
        this.TableName = TABLE_NAME;
    }


    protected override void InitCommandParameters(ref SqlParameterCollection pc)
    {
        pc.Add(new SqlParameter("@Description", SqlDbType.VarChar, 254));
        pc["@Description"].SourceColumn = "Description";

        pc.Add(new SqlParameter("@Published", SqlDbType.Bit));
        pc["@Published"].SourceColumn = "Published";

        pc.Add(new SqlParameter("@SubCount", SqlDbType.Int));
        pc["@SubCount"].SourceColumn = "SubCount";

        pc.Add(new SqlParameter("@StoreLocationID", SqlDbType.VarChar, 36));
        pc["@StoreLocationID"].SourceColumn = "StoreLocationID";
    }

    public virtual string GetStoreLocationID(string nodeID)
    {
        DataSet ds = GetByNodeID(nodeID, true);
        return ds.Tables[0].Rows[0]["StoreLocationID"].ToString();
    }
}


public class ArchivesTreeAccess : SqlTree
{
    public const string TABLE_NAME = "T_ArchivesTree";

    public ArchivesTreeAccess(SqlConnection conn)
        : base(conn)
    {

    }

    protected override void InitTableName()
    {
        this.TableName = TABLE_NAME;
    }


    protected override void InitCommandParameters(ref SqlParameterCollection pc)
    {
        pc.Add(new SqlParameter("@Description", SqlDbType.VarChar, 254));
        pc["@Description"].SourceColumn = "Description";

        pc.Add(new SqlParameter("@QueryCode", SqlDbType.VarChar, 50));
        pc["@QueryCode"].SourceColumn = "QueryCode";

        pc.Add(new SqlParameter("@StoreLocationID", SqlDbType.VarChar, 36));
        pc["@StoreLocationID"].SourceColumn = "StoreLocationID";
    }

    public virtual string GetStoreLocationID(string nodeID)
    {
        DataSet ds = GetByNodeID(nodeID, true);
        return ds.Tables[0].Rows[0]["StoreLocationID"].ToString();
    }
}


public class FeedbackAccess :SqlFeedback
{
    public FeedbackAccess(SqlConnection conn)
        : base(conn)
    {
    }
}


public class BaseAccess : SqlHelper
{

}


public class ShareAccess
{
    public static string ConvertHtml(string html)
    {
        html = HttpUtility.HtmlEncode(html);
        html = html.Replace("\r\n", "<br />");
        return html;
    }

    public static bool SendSMTPEmail(string smtpServer, string fromEmail, string fromPass, string toEmails, string subject, string content)
    {
        try
        {
            //System.Net.Mail.SmtpClient smtpClient = new SmtpClient("smtp.126.com");
            //smtpClient.UseDefaultCredentials = false;
            //smtpClient.Credentials = new System.Net.NetworkCredential("chairui1979", "111112");
            //smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            //MailMessage message = new MailMessage("chairui1979@126.com", "chairui1979@hotmail.com");
            //message.Subject = "Test Subject";
            //message.Body = "Test Body";
            //smtpClient.Send(message);

            MailMessage message = new MailMessage(fromEmail, toEmails, subject, content);
            message.SubjectEncoding = Encoding.GetEncoding("gb2312");
            message.BodyEncoding = Encoding.GetEncoding("gb2312");
            message.IsBodyHtml = true;

            SmtpClient client = new SmtpClient(smtpServer);
            client.UseDefaultCredentials = false;
            client.Credentials = new NetworkCredential(fromEmail.Substring(0, fromEmail.IndexOf('@')), fromPass);
            client.DeliveryMethod = SmtpDeliveryMethod.Network;

            //System.Net.Mail.Attachment data = new System.Net.Mail.Attachment(file, System.Net.Mime.MediaTypeNames.Application.Octet);
            //System.Net.Mime.ContentDisposition disposition = data.ContentDisposition;
            //disposition.CreationDate = System.IO.File.GetCreationTime(file);
            //disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
            //disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
            //message.Attachments.Add(data);
            client.Send(message);
            return true;
        }
        catch
        {
            return false;
        }
    }
}

public class CodeConfigAccess : SqlCodeConfig
{
    public CodeConfigAccess(SqlConnection conn)
        : base(conn)
    {

    }
}


public class CityAccess : SqlTree
{
    public const string TABLE_NAME = "T_City";

    public CityAccess(SqlConnection conn)
        : base(conn)
    {

    }

    protected override void InitTableName()
    {
        this.TableName = TABLE_NAME;
    }


    protected override void InitCommandParameters(ref SqlParameterCollection pc)
    {
        pc.Add(new SqlParameter("@CityLon", SqlDbType.Float));
        pc["@CityLon"].SourceColumn = "CityLon";

        pc.Add(new SqlParameter("@CityLat", SqlDbType.Float));
        pc["@CityLat"].SourceColumn = "CityLat";

        pc.Add(new SqlParameter("@CityZoom", SqlDbType.Int));
        pc["@CityZoom"].SourceColumn = "CityZoom";

        pc.Add(new SqlParameter("@UserCount", SqlDbType.Int));
        pc["@UserCount"].SourceColumn = "UserCount";
    }
}

public class SplitPageAccess : SqlSplitPage
{
    public SplitPageAccess()
        : base()
    {
    }

    public SplitPageAccess(SqlConnection connection, string commandText)
        : base(connection, commandText)
    {
    }
}


public class EventLogAccess : SqlEventLog
{
    public EventLogAccess(SqlConnection conn)
        : base(conn)
    {
    }
}


public class StoreLocationAccess
{
    /// <summary>
    /// 得到资源的本地路径
    /// </summary>
    /// <param name="storeLocationID"></param>
    /// <returns></returns>
    public static string GetLocalDirectory(string storeLocationID)
    {
        return BaseAccess.ExecuteScalar(ConfigManager.ConnectionString,
                "select LocalDirectory from T_StoreLocation where StoreLocationID='" + storeLocationID + "'");
    }

    /// <summary>
    /// 得到资源的相对虚拟目录，返回值不包含任何"/"，"\"
    /// </summary>
    /// <param name="storeLocationID"></param>
    /// <returns></returns>
    public static string GetVirtualDirectory(string storeLocationID)
    {
        string result = BaseAccess.ExecuteScalar(ConfigManager.ConnectionString,
                "select VirtualDirectory from T_StoreLocation where StoreLocationID='" + storeLocationID + "'");
        result = result.TrimStart('\\').TrimEnd('\\').TrimStart('/').TrimEnd('/');
        return result;
    }

    /// <summary>
    /// 取得资源存储本地路径，结尾含"\"
    /// </summary>
    /// <param name="storeLocationID"></param>
    /// <param name="createDate"></param>
    /// <param name="userID"></param>
    /// <returns></returns>
    public static string GetLocalResourceDirectory(string storeLocationID, DateTime createDate, string ID)
    {
        string path = StoreLocationAccess.GetLocalDirectory(storeLocationID);
        path = path.TrimEnd('\\') + "\\";
        path += createDate.ToString("yyyy") + "\\" + createDate.ToString("MM") + "\\" +
            createDate.ToString("dd") + "\\" + ID + "\\";
        return path;
    }


    /// <summary>
    /// 得到资源的名称
    /// </summary>
    /// <param name="storeLocationID"></param>
    /// <returns></returns>
    public static string GetSubject(string storeLocationID)
    {
        return BaseAccess.ExecuteScalar(ConfigManager.ConnectionString,
                "select Subject from T_StoreLocation where StoreLocationID='" + storeLocationID + "'");
    }

    /// <summary>
    /// 创建资源存储本地路径，并且返回创建后的路径，结尾含"\"
    /// </summary>
    /// <param name="storeLocationID"></param>
    /// <param name="createDate"></param>
    /// <param name="userID"></param>
    /// <returns></returns>
    public static string CreateLocalResourceDirectory(string storeLocation, DateTime createDate, string ID)
    {
        string path = GetLocalResourceDirectory(storeLocation, createDate, ID);
        if (!System.IO.Directory.Exists(path))
        {
            System.IO.Directory.CreateDirectory(path);
        }
        return path;
    }


    /// <summary>
    /// 取得资源的URL，结尾不含"/"
    /// </summary>
    /// <param name="categoryID"></param>
    /// <param name="createDate"></param>
    /// <param name="documentID"></param>
    /// <returns></returns>
    public static string GetResourceURL(string storeLocationID, DateTime createDate, string ID)
    {
        string cmdText = "select VirtualDirectory from T_StoreLocation where StoreLocationID='" + storeLocationID + "'";
        string URL = BaseAccess.ExecuteScalar(ConfigManager.ConnectionString, cmdText);
        // VirtualDirectory 在界面输入虚拟目录的时候需要 \ 保证创建虚拟目录正确
        // VirtualDirectory 在URL 中需要 / 保证URL有效，所以转义一下
        URL = URL.Replace('\\', '/');
        URL = URL.TrimStart('\\').TrimEnd('\\').TrimStart('/').TrimEnd('/');
        URL += "/" + createDate.ToString("yyyy") + "/" + createDate.ToString("MM") + "/" +
            createDate.ToString("dd") + "/" + ID;
        return URL;
    }
 

}


public class TagAccess
{
    public SqlConnection Connection;

    public TagAccess(SqlConnection conn)
    {
        Connection = conn;
    }

    public void Add(string tag, string category)
    {
        string[] tags = tag.Split(new char[] { ' ', ',', '，', ';', '；', '|' });
        for (int i = 0; i < tags.Length; i++)
        {
            if (tags[i].Trim().Length > 0)
            {
                //BaseAccess.TryExecuteNonQuery(Connection,
                //    "insert into T_TagStatistic(TagID, Subject, Category, SumCount) values('"+Guid.NewGuid().ToString()+"','" +
                //    tags[i].Trim().Replace("'", string.Empty) + "', '" + category + "', 0)");
                
                string cmdText = "select * from T_TagStatistic where Subject='{0}' and Category='{1}'";
                cmdText = string.Format(cmdText, tags[i], category);
                DataSet ds = BaseAccess.GetDataSet(Connection, cmdText, "T_TagStatistic");
                if (ds.Tables[0].Rows.Count > 0)
                {
                    DataRow row = ds.Tables[0].Rows[0];
                    int count = 0;
                    Int32.TryParse(row["SumCount"].ToString(), out count);
                    row["SumCount"] = count + 1;
                }
                else
                {
                    DataRow row = ds.Tables[0].NewRow();
                    row["TagID"] = Guid.NewGuid().ToString();
                    row["Subject"] = tags[i];
                    row["Category"] = category;
                    row["SumCount"] = 0;
                    ds.Tables[0].Rows.Add(row);
                }
                BaseAccess.UpdateDataSet(Connection, "T_TagStatistic", ds);
            }
        }
    }


    /// <summary>
    /// 返回 True 不受欢迎的
    /// </summary>
    /// <param name="tag"></param>
    /// <param name="category"></param>
    /// <returns></returns>
    public bool IsUnpopular(string tag, string category)
    {
        string cmdText = "select count(*) from T_TagUnpopular where Subject='{0}' and Category='{1}'";
        cmdText = string.Format(cmdText, tag.Replace("'",""), category);
        string result = BaseAccess.ExecuteScalar(Connection, cmdText);
        if ("0".Equals(result))
        {
            return false;
        }
        return true;
    }

}


public class BasePage : System.Web.UI.Page
{
    public string NavigationHtmlCode;
    public SqlConnection Connection;

    public BasePage()
    {
        //Page_PreInit、Page_Init、Page_Load、Page_DataBind、Page_PreRender、Page_Unload、Page_Error、 Page_AbortTransaction 和 Page_CommitTransaction        
        Connection = new SqlConnection(ConfigManager.ConnectionString);
        Connection.Open();
    }

    protected override void OnUnload(System.EventArgs e)
    {
        Connection.Close();
        Connection.Dispose();
    }

    protected void Page_Error(object sender, EventArgs e)
    {
        Exception ex = Server.GetLastError();
        
        SessionManager.ErrorMessage = ex.Message;
        SessionManager.ErrorSource = ex.Source;
        SessionManager.ErrorStackTrace = ex.StackTrace;
        WriteLog("系统", ex.Message + "\r\n" + ex.Source + "\r\n" +ex.StackTrace,
                    Openfree.Framework.DataAccess.LogType.Error, this.GetType().ToString());
    }

    protected virtual void WriteLog(string category, string message, LogTypeEx type, object obj)
    {
        SqlEventLog eventLog = new SqlEventLog(this.Connection);
        string source = obj.GetType().ToString();
        source = source.Replace("ASP.", string.Empty);
        source = source.Replace("_aspx", string.Empty);
        eventLog.Write(category, message, type, source,
            SessionManager.Username,
            Request.UserHostAddress, ConfigManager.EventLogCycleCoutn);
        eventLog.Dispose();
    }



    protected virtual void AddStyle(string cssName)
    {
        string link = "    <link href=\"../App_Themes/" + Page.Theme +
            "/{0}\" type=\"text/css\" rel=\"stylesheet\" />\r\n";
        Literal lit = new Literal();
        lit.Text = string.Format(link, cssName);
        Page.Header.Controls.Add(lit);
        //样式表在html文件下有效，在aspx文件下无效，将样式表用记事本保存UTF-8格式即可
    }

    /// <summary>
    /// Virtual Application Root Path
    /// 
    /// 开发状态 http://localhost:12345/website/index.aspx
    /// Request.ApplicationPath : "/website"
    /// 发布状态 http://localhost:website/index.aspx
    /// Request.ApplicationPath : "/"    
    /// 如果返回值为 "/" 返回 string.Empty;
    /// </summary>
    public string ApplicationPath
    {
        get
        {
            string result = Request.ApplicationPath;
            if ("/".Equals(Request.ApplicationPath))
            {
                result = string.Empty;
            }
            return result;
        }
    }

    /// <summary>
    /// 截断字符串并在字符串后面添加"..."
    /// </summary>
    /// <param name="value"></param>
    /// <param name="cutIndex"></param>
    /// <returns></returns>
    protected virtual string FormatSubject(object value, int cutIndex)
    {
        return ConvertEx.FormatSubject(value, cutIndex);
    }
   
    /// <summary>
    /// 格式化Boolean类型数据，返回实际说明文字。
    /// </summary>
    /// <param name="value">1/0 true/false 对于字符类型的值不区分大小写</param>
    /// <param name="convertTrue"></param>
    /// <param name="convertFalse"></param>
    /// <returns></returns>
    protected virtual string FormatBoolean(object value, string convertTrue, string convertFalse)
    {
        return ConvertEx.FormatBoolean(value, convertTrue, convertFalse);
    }

    protected virtual string FormatZero(string value)
    {
        if (value == "0.0000")
        {
            return "0";
        }
        else if (value.LastIndexOf("00")>-1)
        {
            return value.Remove(value.Length - 2);
        }
        else
        {
            return value;
        }
    }   

    /// <summary>
    /// 隐藏某些不需要显示的Column
    /// </summary>
    /// <param name="gridView"></param>
    /// <param name="column">仅显示的Column</param>
    public static void HideGridViewColumn(GridView gridView, string[] column)
    {
        foreach (DataControlField gridColumn in gridView.Columns)
        {
            if (gridColumn is BoundField)
            {
                gridColumn.Visible = true;
            }
        }

        foreach (DataControlField gridColumn in gridView.Columns)
        {
            if (gridColumn is BoundField)
            {
                bool flag = true;
                string boundField = ((BoundField)gridColumn).DataField;
                foreach (string col in column)
                {
                    if (col == boundField)
                    {
                        flag = false;
                        break;
                    }
                }
                gridColumn.Visible = true;
                if (flag)
                {
                    gridColumn.Visible = false;
                }
            }
        }
    }

    /// <summary>
    /// 回车换行转换为<br />
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    protected virtual string TextToHtml(object value)
    {
        string result = value.ToString();
        result = HttpUtility.HtmlEncode(result);        
        result = result.Replace(" ", "&nbsp;&nbsp;");
        result = result.Replace("\r\n", "<br />");
        return result;
    }

    /// <summary>
    /// JS的消息对话窗口
    /// </summary>
    /// <param name="message"></param>
    protected virtual void Alert(string message)
    {
        message = message.Replace("\r\n", "\r");
        message = message.Replace("'", "\\'");
        Page.ClientScript.RegisterStartupScript(this.GetType(),
                "alert", JavaScript.Alert(message));
    }

    /// <summary>
    /// JS的消息对话窗口，AJAX专用
    /// </summary>
    /// <param name="message"></param>
    protected virtual void Alert(Control control, string message)
    {
        message = message.Replace("\r\n", "\r");
        message = message.Replace("'", "\\'");
        ScriptManager.RegisterStartupScript(control, this.GetType(),
                "alert", "alert('" + message + "');", true);
    }

    
}


public class BaseUserControl : System.Web.UI.UserControl
{
    public SqlConnection Connection;

    public BaseUserControl()
    {
        Connection = new SqlConnection(ConfigManager.ConnectionString);
        Connection.Open();
    }

    public override void Dispose()
    {
        Connection.Close();
        Connection.Dispose();
    }

    protected override void OnUnload(System.EventArgs e)
    {
        //Connection.Close();
        //Connection.Dispose();
    }

    /// <summary>
    /// Virtual Application Root Path
    /// 
    /// 开发状态 http://localhost:12345/website/index.aspx
    /// Request.ApplicationPath : "/website"
    /// 发布状态 http://localhost:website/index.aspx
    /// Request.ApplicationPath : "/"    
    /// 如果返回值为 "/" 返回 string.Empty;
    /// </summary>
    public string ApplicationPath
    {
        get
        {
            string result = Request.ApplicationPath;
            if ("/".Equals(Request.ApplicationPath))
            {
                result = string.Empty;
            }
            return result;
        }
    }
    protected void BindDropDownList(Openfree.Framework.WebControl.DropDownList control, DataSet ds, bool AddEmpty)
    {
        if (ds != null && ds.Tables.Count > 0)
        {
            control.DataSource = ds.Tables[0];
            control.DataTextField = "CodeName";
            control.DataValueField = "CodeValue";
            control.DataBind();
        }
        if (AddEmpty)
        {
            control.Items.Insert(0, new ListItem("请选择", ""));
        }
        if (control.Items.Count > 0)
        {
            control.SelectByValue = string.Empty;
        }
    }
    /// <summary>
    /// JS的消息对话窗口
    /// </summary>
    /// <param name="message"></param>
    protected virtual void Alert(string message)
    {
        message = message.Replace("\r\n", "\r");
        message = message.Replace("'", "\\'");
        Page.ClientScript.RegisterStartupScript(this.GetType(),
                "alert", JavaScript.Alert(message));
    }

    protected virtual void WriteLog(string category, string message, LogTypeEx type, object obj)
    {
        SqlEventLog eventLog = new SqlEventLog(this.Connection);
        string source = obj.GetType().ToString();
        source = source.Replace("ASP.", string.Empty);
        source = source.Replace("_aspx", string.Empty);
        eventLog.Write(category, message, type, source,
            SessionManager.Username,
            Request.UserHostAddress, ConfigManager.EventLogCycleCoutn);
        eventLog.Dispose();
    }
}

public class ProductAccess
{
    //public static void AddViewCount(string documentID)
    //{
    //    documentID = documentID.Replace(",", string.Empty);
    //    BaseAccess.ExecuteNonQuery(ConfigManager.ConnectionString,
    //        "update T_Document set ViewCount = ViewCount + 1 where DocumentID='" + documentID + "'");
    //}

    public static void AddViewCount(string productCode)
    {
        string cmdText = "update T_Product set ViewCount = ViewCount + 1 where ProductCode='{0}'";
        BaseAccess.ExecuteNonQuery(ConfigManager.ConnectionString, cmdText);
    }
    
    /// <summary>
    /// 验证ProductCode是否为一，如果存在返回True，如果不存在返回False
    /// </summary>
    /// <param name="ProductCode"></param>
    /// <returns></returns>
    public static bool ValidateProductCode(string productCode)
    {
        string result = "select ProductCode from T_Product where ProductCode='{0}'";
        result = string.Format(result, productCode);
        result = BaseAccess.ExecuteScalar(ConfigManager.ConnectionString, result);
        if (string.IsNullOrEmpty(result))
        {
            return false;
        }
        else
        {
            return true;
        }
    }

    /// <summary>
    /// 验证ProductCode是否为一，如果存在返回True，如果不存在返回False
    /// </summary>
    /// <param name="ProductCode"></param>
    /// <returns></returns>
    public static bool ValidateProductCode(string productID, string productCode)
    {
        string result = "select ProductCode from T_Product where ProductCode<>'{0}' and ProductCode='{1}'";
        result = string.Format(result, productID, productCode);
        result = BaseAccess.ExecuteScalar(ConfigManager.ConnectionString, result);
        if (string.IsNullOrEmpty(result))
        {
            return false;
        }
        else
        {
            return true;
        }
    }

    public static DataSet GetDataSet(string productID)
    {
        return BaseAccess.GetDataSet(ConfigManager.ConnectionString,
                "select * from T_Product where ProductID = '" + productID + "'", "T_Product");
    }

    public static DataSet GetEmptyDataSet()
    {
        return BaseAccess.GetDataSet(ConfigManager.ConnectionString,
                "select * from T_Product where 1=2", "T_Product");
    }    
}

public class ProductCategoryAccess : SqlTree
{
    public const string TABLE_NAME = "T_ProductCategory";

    public ProductCategoryAccess(SqlConnection conn)
        : base(conn)
    {

    }

    protected override void InitTableName()
    {
        this.TableName = TABLE_NAME;
    }


    protected override void InitCommandParameters(ref SqlParameterCollection pc)
    {
        pc.Add(new SqlParameter("@Description", SqlDbType.VarChar, 254));
        pc["@Description"].SourceColumn = "Description";

        pc.Add(new SqlParameter("@Published", SqlDbType.Bit));
        pc["@Published"].SourceColumn = "Published";

        pc.Add(new SqlParameter("@SubCount", SqlDbType.Int));
        pc["@SubCount"].SourceColumn = "SubCount";

        pc.Add(new SqlParameter("@StoreLocationID", SqlDbType.VarChar, 36));
        pc["@StoreLocationID"].SourceColumn = "StoreLocationID";
    }

    public virtual string GetStoreLocationID(string nodeID)
    {
        DataSet ds = GetByNodeID(nodeID, true);
        return ds.Tables[0].Rows[0]["StoreLocationID"].ToString();
    }
}


public class ProductImageAccess
{
    public static DataSet GetEmptyDataSet()
    {
        return BaseAccess.GetDataSet(ConfigManager.ConnectionString,
                "select * from T_ProductImage where 1=2", "T_ProductImage");
    }

    public static DataSet GetDataSet(string productID)
    {
        return BaseAccess.GetDataSet(ConfigManager.ConnectionString,
                "select * from T_ProductImage where ProductID = '" + productID + "'", "T_ProductImage");
    }

    public static DataSet GetDataSet(string productID, string Category)
    {
        return BaseAccess.GetDataSet(ConfigManager.ConnectionString,
                "select * from T_ProductImage where ProductID = '" + productID +
                "' and Category='" + Category + "'", "T_ProductImage");
    }

    public static string GetLargeImageFileName(string productID)
    {
        return BaseAccess.ExecuteScalar(ConfigManager.ConnectionString,
            "select LargeImageFileName from T_ProductImage where Category='index' and ProductID='" + productID + "'");
    }

    public static string GetThumbImageFileName(string productID)
    {
        return BaseAccess.ExecuteScalar(ConfigManager.ConnectionString,
            "select ThumbImageFileName from T_ProductImage where Category='index' and ProductID='" + productID + "'");
    }
}



public class OrgTreeAccess : SqlTree
{
    public const string TABLE_NAME = "T_OrgTree";
    public static string TREE_XINGZHENG = "XingZheng";

    public OrgTreeAccess(SqlConnection conn)
        : base(conn)
    {

    }

    protected override void InitTableName()
    {
        this.TableName = TABLE_NAME;
    }


    protected override void InitCommandParameters(ref SqlParameterCollection pc)
    {
        pc.Add(new SqlParameter("@OrgID", SqlDbType.VarChar, 36));
        pc["@OrgID"].SourceColumn = "OrgID";

        pc.Add(new SqlParameter("@QueryCode", SqlDbType.VarChar, 50));
        pc["@QueryCode"].SourceColumn = "QueryCode";

        pc.Add(new SqlParameter("@Alias", SqlDbType.VarChar, 50));
        pc["@Alias"].SourceColumn = "Alias";

        pc.Add(new SqlParameter("@IsVirtual", SqlDbType.Bit));
        pc["@IsVirtual"].SourceColumn = "IsVirtual";

        pc.Add(new SqlParameter("@Description", SqlDbType.VarChar, 50));
        pc["@Description"].SourceColumn = "Description";
    }

    public static string GetQueryCode(string userID, string orgTreeCategory)
    {
        return BaseAccess.ExecuteScalar(ConfigManager.ConnectionString,
            "select QueryCode from T_OrgTree where Category='" + orgTreeCategory +
            "' and OrgID=(select OrgID from T_OrgUser where UserID='" + userID + "')");
    }
}